// el下拉框选项列表转为对象
export const list2Obj = (list = []) => {
  const obj = {}
  if (list && list.length) {
    list.forEach(({ value, label }) => {
      obj[value] = label
    });
  }
  return obj
}

// 通过表单项生成初始值对象
export const getInitialFieldsValue = (list) => {
  const obj = {}
  list.flat().forEach(({ prop, type, multiple, defaultValue }) => {
    const isMultiple = ['select', 'managementArea', 'provinceSelect'].includes(type) && multiple
    const isRange = ['datePicker', 'datePicker', 'numberRange'].includes(type)
    if (isRange || isMultiple) {
      obj[prop] = []
    } else if (type == 'number') {
      obj[prop] = defaultValue
    } else if (type == 'select') {
      obj[prop] = defaultValue || null
    } else {
      obj[prop] = typeof defaultValue !== 'undefined' ? defaultValue : ''
    }
  });
  return obj
}

// 过滤数据空值返回undefined
export const compactObj = (targetObj, compareObj) => {
  const data = {}
  if (!targetObj) {
    return data
  }
  for (let [key, value] of Object.entries(targetObj)) {
    const obj = {}
    if (Array.isArray(value)) {
      data[key] = value
    } else if (value) {
      if (compareObj[key]) {
        for (let [k, v] of Object.entries(value)) {
          if (typeof compareObj[key][k] === 'undefined' && v === '') {
            obj[k] = undefined
          } else if (`${v}` === '0') {
            obj[k] = v
          } else {
            obj[k] = v || compareObj[key][k]
          }
        }
        data[key] = obj
      } else {
        data[key] = value
      }
    } else {
      data[key] = value
    }
  }
  return data
}

// 过滤多余表单项
// 过滤对象数组，每项清除匹配到ids
export const filterArrObjItems = (list = [], ids = 'id,_X_ROW_KEY,serviceArea,serviceAreaIds,validationErrors') => {
  return list.map((item) => {
    return filterObjItems(item, ids)
  })
}

// 过滤对象，每项清除匹配到ids
export const filterObjItems = (data = {}, ids = 'id,_X_ROW_KEY,serviceArea,serviceAreaIds,validationErrors') => {
  const obj = Object.create(null)
  const arr = ids.split(',')
  for (let [key, value] of Object.entries(data)) {
    if (!arr.includes(key)) {
      obj[key] = value
    }
  }
  return obj
}

/**
 * @description 格式化日期
 * @param0 {Date}  时间，默认为当前时间
 * @param1 {String} 日期分隔符，默认不分割
 * @param2 {Number} 12或24时间制
 * @param3 {String} 是否返回时间
 * @return {String}
 */
export const formatDate = (time, separator, system, format) => {
  time = time ? (typeof time === 'string' ? new Date(time) : time) : new Date()
  separator = separator || '-'
  system = system || 24
  format = format || 'DATETIME'

  let year = time.getFullYear()
  let month = time.getMonth() + 1
  let date = time.getDate()
  let hour = time.getHours()
  let minute = time.getMinutes()
  let second = time.getSeconds()
  if (system == 12) {
    hour = hour > 12 ? hour - 12 : hour
  }
  switch (format) {
    case 'DATE':
      return [year, month, date].map(formatNumber).join(separator)
    case 'TIME':
      return [hour, minute, second].map(formatNumber).join(':')
    default:
      return [year, month, date].map(formatNumber).join(separator) + ' ' + [hour, minute, second].map(formatNumber).join(
        ':')
  }
}

/**
 * @description 格式化数字，各位数字补0
 * @param {Number}
 */
const formatNumber = (num) => {
  num = num.toString()
  return num[1] ? num : '0' + num
}

/**
 * @description 格式化数字，转化为百分数
 * @param0 {Number}
 * @param1 {Number}
 * @return {String}
 */
export const toPercent = (num, digits) => {
  if (digits) {
    return `${toFixed(num * 100, digits)}%`
  }
  return `${Number(num * 100)}%`
}

/**
 * @description 格式化数字，保留2位小数
 * @param0 {Number}
 * @param1 {Number}
 * @return {Number}
 */
export const toFixed = (num, digits = 2) => {
  return Number.isInteger(num) ? num : Number(num).toFixed(digits)
}

/**
 * 表格数据为空的数据替换为目标字符串
 * @param {* 表格数据} list Array
 * @param {* 空值字符串} placeholder String
 * @returns 表格数据
 */
export const replaceNullItems = (list, placeholder = '-') => {
  list = list || [];
  return list.map(item => {
    const obj = {}
    for (let [k, v] of Object.entries(item)) {
      const isEmpty = v === null || typeof v === 'undefined' || v === ''
      obj[k] = isEmpty ? placeholder : v
    }
    return obj
  })
}

// 判断URL地址
export const isUrl = (url) => {
  // eslint-disable-next-line no-useless-escape
  return /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/.test(url)
}

// 英文括号转中文括号
export const enToZhForBracket = (str) => {
  // eslint-disable-next-line no-useless-escape
  return str.replace(/[\(]/g, '（').replace(/[\)]/g, '）')
}
// 英文括号转中文括号
export const enToZhForContent = (content) => {
  const regexChines = new RegExp('[\\u4E00-\\u9FFF]+', 'g');
  if (regexChines.test(content)) {
    content = content.replace(' ', '').replace('　', '').replace('(', '（').replace(')', '）').replace('\t', '');
  } else {
    // 2.纯英文名称的：//符号统一转为英文符号，纯英文名称的不去除空格
    content = content.replace('，', ',').replace('。', '.').replace('；', ';').replace('：', ':').replace('（', '(').replace('）', ')');
  }
  return content;
}

// 获取时间戳
export const getTimeStamp = (time) => {
  return new Date(time).getTime()
}

// 结账区间 id: name
const CHECKOUT_RANGE_MAPS = {
  40910: 120,
  1101: 0,
  1102: 5,
  1103: 7,
  1104: 10,
  1105: 15,
  1106: 20,
  1107: 30,
  1108: 45,
  1109: 60,
  1110: 90,
  40747: 65,
}

// 计算账期天数
// checkoutTime 结账时间 42:6-12日 43:16-20日 44:26-30日 45:6-12日和26-30日各结一次 40289:非固定日结账
// sysDict: 15
// paidType 付款方式 40294:预付款 40295:带款提货 40296:货到付款 40297:票到付款 40298:背靠背付款
// sysDict: 10131
// checkoutRange 结账区间
// sysDict: 10133
export const getFiscalPeriodDays = (supplierContractBill, data) => {
  // 结账时间 = 40289 && 付款方式 = (40295 || 40298) 账期天数 = 0
  // 结账时间 = 40289 && 付款方式 = (40296 || 40297) 账期天数 = 结账区间
  // 结账时间 = 40289 && 付款方式 = 40294 账期天数 = -15
  // 结账时间 = (42 || 43 || 44) && 付款方式 = (40296 || 40297) 账期天数 = 结账区间 + 15
  // 结账时间 = 45 && 付款方式 = (40296 || 40297) 账期天数 = 结账区间 + 7
  const { checkoutTime, paidType, checkoutRange } = supplierContractBill;
  let fiscalPeriodDays = null;
  if (checkoutTime == 40289) {
    if ([40295, 40298].includes(paidType)) {
      fiscalPeriodDays = 0
    }
    if ([40296, 40297].includes(paidType)) {
      fiscalPeriodDays = checkoutRange ? CHECKOUT_RANGE_MAPS[checkoutRange] : null
    }
    if (paidType == 40294) {
      fiscalPeriodDays = -15
    }
  }
  if ([42, 43, 44].includes(checkoutTime) && [40296, 40297].includes(paidType)) {
    fiscalPeriodDays = checkoutRange ? CHECKOUT_RANGE_MAPS[checkoutRange] + 15 : null
  }
  if (checkoutTime == 45 && [40296, 40297].includes(paidType)) {
    fiscalPeriodDays = checkoutRange ? CHECKOUT_RANGE_MAPS[checkoutRange] + 7 : null
  }
  supplierContractBill.fiscalPeriodDays = fiscalPeriodDays
  data.fiscalPeriodDays = fiscalPeriodDays
}

// 初始话查询表单条件
export const getFormDataFieldsValue = (formItemList) => {
  const obj = {}
  formItemList.flat().forEach(({ prop, type, multiple, defaultValue }) => {
    const isMultiple = ['select', 'managementArea', 'provinceSelect'].includes(type) && multiple
    const isRange = ['datePicker', 'numberRange'].includes(type)
    if (isRange || isMultiple) {
      obj[prop] = []
    } else if (['number', 'select'].includes(type)) {
      obj[prop] = defaultValue || null
    } else {
      obj[prop] = typeof defaultValue !== 'undefined' ? defaultValue : ''
    }
  });
  return obj
}
